package com.example.crossborderecommerce.controller;

import com.example.crossborderecommerce.entity.ChatMsg;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.client.RestTemplate;
import org.springframework.http.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CopyOnWriteArrayList;

/**
 * 聊天机器人模块
 */

@RestController
@Transactional
@RequestMapping("/chatbot")
public class ChatBotController {
    @Value("${baidu.api.key}")
    public String apiKey;

    @Value("${baidu.secret.key}")
    public String secretKey;

    private static final String BAIDU_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token";

    // ernie-4.0-8k-preview https://cloud.baidu.com/doc/WENXINWORKSHOP/s/nluv1jxlp
    private static final String CHAT_URL = "https://aip.baidubce.com/rpc/2" +
            ".0/ai_custom/v1/wenxinworkshop/chat/ernie-4.0-8k-preview";

    private final RestTemplate restTemplate;

    private final CopyOnWriteArrayList<SseEmitter> emitters = new CopyOnWriteArrayList<>();

    public ChatBotController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    /**
     * 获取 access_token
     */
    public String getAccessToken() {
        String url = BAIDU_TOKEN_URL + "?grant_type=client_credentials&client_id=" + apiKey + "&client_secret=" + secretKey;
        ResponseEntity<String> response = restTemplate.getForEntity(url, String.class);
        // 解析响应获取 access_token
        JSONObject jsonObject = new JSONObject(response.getBody());
        return jsonObject.get("access_token").toString();
    }

    /**
     * 流式对话
     */
    @PostMapping("/stream-chat")
    public SseEmitter streamingChat(@RequestBody List<ChatMsg> messages) {
        SseEmitter emitter = new SseEmitter();
        CompletableFuture.runAsync(() -> {
            try {
                String access_token = getAccessToken();
                String url = CHAT_URL + "?access_token=" + access_token;
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("messages", new JSONArray(messages));
                jsonObject.put("stream", true);
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                HttpEntity<String> entity = new HttpEntity<>(jsonObject.toString(), headers);

                // 调用第三方 API
                restTemplate.execute(url, HttpMethod.POST,
                        request -> {
                            request.getHeaders().putAll(headers);
                            request.getBody().write(entity.getBody().getBytes(StandardCharsets.UTF_8));
                        },
                        response -> {
                            BufferedReader reader = new BufferedReader(new InputStreamReader(response.getBody()));
                            String line;
                            while ((line = reader.readLine()) != null) {
                                if (line.trim().isEmpty()) continue;
                                try {
                                    System.out.println(line.trim().substring(5));
                                    emitter.send(line.trim().substring(5));
                                } catch (IOException e) {
                                    emitter.completeWithError(e);
                                    return null;
                                }
                            }
                            emitter.complete();
                            return null;
                        });
            } catch (Exception e) {
                emitter.completeWithError(e);
            }
        });

        return emitter;
    }
}